<?php

namespace mpend\modules\user\models;

use Yii;
use yii\helpers\Inflector;
use common\helpers\Url;
use common\models\work\WorkCategory;

/**
 * 个人信息修改模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ProfileForm extends \common\base\FormModel {

    /**
     * @var string 头像
     */
    public $avatar;

    /**
     * @var string 昵称
     */
    public $nickname;

    /**
     * @var integer 性别
     */
    public $gender = 0;

    /**
     * @var date 出生日期
     */
    public $birthday;

    /**
     * @var string 位置
     */
    public $location;

    /**
     * @var string 个人签名
     */
    public $signature;

    /**
     * @var string 数据原型模型
     */
    public function getInstanceModelClass() {
        return Yii::$app->user->identityClass;
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            ['avatar', 'string', 'max' => 255],
            ['nickname', 'string', 'max' => 30],
            ['gender', 'in', 'range' => [0, 1, 2]],
            ['birthday', 'date', 'format' => 'yyyy-MM-dd'],
            [['location'], 'string', 'max' => 50],
            [['signature'], 'string', 'max' => 128],
            [['avatar'], 'validateAvatar'],
            [['nickname', 'location', 'signature'], '\common\validators\WordFilterValidator'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'nickname' => '姓名',
            'gender' => '性别',
            'avatar' => '头像',
            'birthday' => '出生日期',
            'location' => '地点',
            'signature' => '个人签名',
        ];
    }

    /**
     * @inheritdoc
     */
    public function validateAvatar($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $this->$attribute = Url::filterRelative($this->$attribute);
    }

    /**
     * @inheritdoc
     */
    public function attributeHints() {
        return [
            'nickname' => '好名字可以让你的朋友更容易记住你',
            'location' => '开启定位权限后可直接获取您的位置信息',
            'signature' => '一句话你的状态',
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeTitles() {
        return [
            'nickname' => '设置姓名',
            'gender' => '设置性别',
            'avatar' => '更改头像',
            'birthday' => '设置出生日期',
            'location' => '位置信息',
            'signature' => '编辑个人签名',
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeInputTypes() {
        return [
            'gender' => 'radio',
            'avatar' => 'uploader',
            'birthday' => 'date',
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributePlaceholders() {
        return [
            'nickname' => '未设置',
            'gender' => '未设置',
            'avatar' => Url::attach(''),
            'birthday' => '未设置',
            'location' => '未设置',
            'signature' => '无',
        ];
    }

    /**
     * Returns the text title for the specified attribute.
     * @param string $attribute the attribute name
     * @return string the attribute label
     * @see generateAttributeLabel()
     * @see attributeLabels()
     */
    public function getAttributeInputType($attribute) {
        $inputTypes = $this->attributeInputTypes();
        return isset($inputTypes[$attribute]) ? $inputTypes[$attribute] : 'text';
    }

    /**
     * @inheritdoc
     */
    public function setExtraAttributes($model) {
        if ($model->meta) {
            $this->setAttributes($model->meta->attributes);
        }
    }

    /**
     * @inheritdoc
     */
    public function beforeValidate() {
        if (!parent::beforeValidate()) {
            return false;
        }
        if ($this->getIsNewRecord()) {
            return false;
        }
        return true;
    }

    /**
     * @return \common\models\user\User|null
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        /* @var $model \common\models\user\User */
        $model = $this->getModel();
        if (!$model) {
            return $this->dumpError('用户不存在或者当前未登陆', false);
        }
        $attributes = array_filter($this->attributes);
        $model->setAttributes($attributes);

        /* @var $meta \common\models\user\UserMeta */
        $meta = $model->meta;
        $meta->setAttributes($attributes);
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $this->setDirtyAttributes($model);
            if (!$model->save()) {
                return $this->dumpError('联系信息保存失败');
            }
            $this->setDirtyAttributes($meta);
            if (!$meta->save()) {
                return $this->dumpError('认证信息保存失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        if ($this->useDirty) {
            $updates = [];
            foreach ($this->getDirtyAttributes() as $attribute => $value) {
                $updates[] = $this->getAttributeOptions($attribute);
            }
            return [
                'updated' => $updates,
                'user' => $model
            ];
        }
        return $model;
    }

    public function getWorkTypeIdList() {
        return WorkCategory::getMultiListOptions();
    }

    public function getAttributeOptions($name) {
        $attributes = $this->attributes;
        if (!array_key_exists($name, $attributes)) {
            return null;
        }
        $value = $this->$name;
        $options = [];
        $type = $this->getAttributeInputType($name);
        if ($type === 'radio' || $type === 'multipicker') {
            $attributeName = preg_replace("/\[.*\]/", '', $name);
            $property = Inflector::variablize($attributeName) . 'List';
            if ($this->hasProperty($property)) {
                $options = $this->$property;
            }
        }
        if ($type === 'uploader') {
            $value = Url::attach($value);
        }
        return [
            'attribute' => $name,
            'type' => $type,
            'options' => $options,
            'title' => $this->getAttributeTitle($name),
            'label' => $this->getAttributeLabel($name),
            'hint' => $this->getAttributeHint($name),
            'value' => $value,
            'original' => $value,
            'placeholder' => $this->getAttributePlaceholder($name),
        ];
    }

    public function getOptionAttributes() {
        return [
            'avatar',
            'nickname',
//            'gender',
//            'birthday',
//            'location',
            'signature',
        ];
    }

    public function options($attribute = null) {
        if ($attribute) {
            return $this->getAttributeOptions($attribute);
        }
        $attributes = $this->getOptionAttributes();
        $data = [];
        foreach ($attributes as $attribute) {
            if ($attribute == 'id') {
                continue;
            }
            $options = $this->getAttributeOptions($attribute);
            if ($options) {
                $data[] = $this->getAttributeOptions($attribute);
            }
        }
        return $data;
    }

}
